layui.define(['jquery', 'util', 'layer'], function (exports) {

    var $ = layui.$, util = layui.util, layer = layui.layer;

    var model_name = "myNumber",
        input_elem = 'input[lay-skin=mynumber]',
        baseClassName = 'layui-input-number',
        numberInputBtn = [
            '<div class="layui-number-input-btn">',
            '<i class="layui-icon layui-icon-up"  lay-click="numberUp"></i>',
            '<i class="layui-icon layui-icon-down" lay-click="numberDown"></i>',
            '</div>',
        ].join(''),
        style = [
            '<style type="text/css">',
            '.layui-number-input-container{position:relative;width:100%;}',
            '.' + baseClassName + '::-webkit-outer-spin-button,.' + baseClassName + '::-webkit-inner-spin-button{-webkit-appearance: none;}',
            '.' + baseClassName + '{-moz-appearance: textfield;padding:0px 25px 0px 5px;text-align:center;}',
            '.' + baseClassName + '-no{-moz-appearance: textfield;padding:0px 5px 0px 5px;text-align:center;}',
            '.layui-number-input-btn{position:absolute;top:1px;right:2px;width:20px;height:36px;}',
            '.layui-number-input-btn i{position:absolute;width:20px;height:17.5px;bottom:0;border-left:1px solid #eee;color:#999;border-radius:0px 0px 2px 0px;font-size:12px;text-align:center;line-height:18px;cursor: pointer;}',
            '.layui-number-input-btn i:first-child{top:0px;border-bottom:1px solid #eee;border-radius:0px 2px 0px 0px}',
            '.layui-number-input-btn i:hover{background:#eee;}',
            '.layui-number-input-container .layui-input{width:100%}',
            '.layui-input-sm .layui-input{height:28px;}',
            '.layui-input-sm .layui-number-input-btn{position:absolute;top:0;right:2px;width:20px;height:28px;}',
            '.layui-input-sm .layui-number-input-btn i{position:absolute;width:20px;height:12.5px;bottom:0;border:1px solid #eee;color:#999;border-radius:0px 0px 2px 0px;font-size:8px;text-align:center;line-height:13px;cursor: pointer;}',
            '</style>'
        ].join('');
    $('head link:last')[0] && $('head link:last').after(style) || $('head').append(style);

    var obj = {
        options: {
            elem: input_elem//绑定的元素
            , step: 1//默认加减数
            , readonly: false//默认可以输入
            , size: 'md'
        },
        //初始化
        render: function (option) {
            var _this = this;
            _this.options = $.extend(_this.options, option);

            $(_this.options.elem).not('[lay-ignore]').addClass(baseClassName).wrap('<div class="layui-number-input-container"></div>');
            $(_this.options.elem).not('[lay-ignore]').after(numberInputBtn);
            $(_this.options.elem).filter('[size=sm]').parent().addClass("layui-input-sm");
            if (_this.options.size == 'sm')$(".layui-number-input-container").addClass("layui-input-sm");
            //定义只读，不允许输入
            if (_this.options.readonly)$(_this.options.elem).attr("readonly", true);
            $(_this.options.elem).removeClass("layui-hide").addClass("layui-input");
            _this.listen();
        },
        //监听
        listen: function () {
            var _this = this;
            //直接修改了内容
            $(_this.options.elem).bind('input propertychange', function () {
                var value = $(this).val();
                $(this).val(value.replace(/[^\.?\d]/g, ''));
                value = $(this).val();
                var maxValue = $(this).attr('max') || _this.options.max;
                var minValue = $(this).attr("min") || _this.options.min;
                if (value > maxValue) layer.tips('最大值' + maxValue, $(this), {tips: 1});
                if (value < minValue) layer.tips('最小值' + minValue, $(this), {tips: 1});
            });

            var timeOut;
            //长按
            $('[lay-click="numberUp"],[lay-click="numberDown"]').mousedown(function () {
                var $this = $(this);
                timeOut = setInterval(function () {
                    $this.trigger('click');
                }, 200);
            });
            //鼠标
            $('[lay-click="numberUp"],[lay-click="numberDown"]').mouseup(function () {
                clearInterval(timeOut);
            });//鼠标离开
            $('[lay-click="numberUp"],[lay-click="numberDown"]').mouseout(function () {
                clearInterval(timeOut);
            });

            //右边两个上下键点击
            util.event('lay-click', {
                numberUp: function (othis) {
                    var thisInput = othis.parent().parent().children('.' + baseClassName);
                    var step = thisInput.attr('step') || _this.options.step || 1;
                    var minValue = thisInput.attr('min') || _this.options.min;
                    var maxValue = thisInput.attr('max') || _this.options.max;
                    minValue = parseInt(minValue);
                    maxValue = parseInt(maxValue);
                    var thisInputValue = thisInput.val();
                    if (!thisInputValue) {
                        thisInput.val('').focus().val(minValue);
                        return;
                    }
                    //最大值大于设定
                    if (maxValue != undefined) {
                        if (thisInputValue >= maxValue) {
                            layer.tips('最大值' + maxValue, thisInput, {tips: 1});
                            return false;
                        }
                    }
                    thisInputValue = _this.add(thisInputValue, parseFloat(step));
                    thisInput.val('').focus().val(thisInputValue);
                },
                numberDown: function (othis) {
                    var thisInput = othis.parent().parent().children('.' + baseClassName);
                    var step = thisInput.attr('step') || _this.options.step || 1;
                    var minValue = thisInput.attr('min') || _this.options.min;
                    minValue = parseInt(minValue);
                    var thisInputValue = thisInput.val();
                    if (!thisInputValue) {
                        thisInput.val('').focus().val(minValue);
                        return;
                    }
                    if (minValue != undefined) {
                        if (thisInputValue <= minValue) {
                            layer.tips('最小值' + minValue, thisInput, {tips: 1});
                            return false;
                        }
                    }
                    thisInputValue = _this.subtraction(thisInputValue, parseFloat(step));
                    thisInput.val('').focus().val(thisInputValue);
                }
            });
        },
        /**
         * 加法
         * @param arg1
         * @param arg2
         * @returns {number}
         */
        add: function (arg1, arg2) {
            var r1, r2, m;
            try {
                r1 = arg1.toString().split(".")[1].length;
            } catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split(".")[1].length;
            } catch (e) {
                r2 = 0;
            }
            m = Math.pow(10, Math.max(r1, r2));
            return (this.multiplication(arg1, m) + this.multiplication(arg2, m)) / m;
        },
        /**
         * 减法
         * @param arg1 被减数
         * @param arg2 减数
         * @returns {string}
         */
        subtraction: function (arg1, arg2) {
            var r1, r2, m, n;
            try {
                r1 = arg1.toString().split(".")[1].length;
            } catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split(".")[1].length;
            } catch (e) {
                r2 = 0;
            }
            m = Math.pow(10, Math.max(r1, r2));
            //last modify by deeka
            //动态控制精度长度
            n = (r1 >= r2) ? r1 : r2;
            return ((arg1 * m - arg2 * m) / m).toFixed(n);
        },
        /**
         * 乘法
         * @param arg1
         * @param arg2
         * @returns {number}
         */
        multiplication: function (arg1, arg2) {
            var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
            try {
                m += s1.split(".")[1].length;
            } catch (e) {
            }
            try {
                m += s2.split(".")[1].length;
            } catch (e) {
            }
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
        }
    };
    //外部接口
    exports(model_name, obj);
});